package com.seeyon.apps.kkARPEvent.util;

import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.file.model.CtpLocalFile;
import com.seeyon.ctp.common.htmltopdf.interceptor.HtmlToPdfInterceptor;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.concurrent.ExecutorServiceFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * Title :
 * Author: chenxd
 * Date: 2023-12-4 11:13
 */
public class Html2PDFExecute {
    private static Html2PDFExecute instance;
    public static Html2PDFExecute getInstance(){
        if(instance == null){
            synchronized (Html2PDFExecute.class){
                if(instance == null){
                    instance = new Html2PDFExecute();
                }
            }
        }
        return instance;
    }
    private static final Log logger = LogFactory.getLog(Html2PDFExecute.class);
    private static boolean initialized = false;
    private static String toPdfTool = SystemEnvironment.getApplicationFolder() + File.separator + "print"
            + File.separator + "tools" + File.separator + "windows" + File.separator + "wkhtmltopdf.exe";
    private static void init() {
        try {
        	logger.info("转pdf得到的osName================================"+System.getProperty("os.name"));
            if (System.getProperty("os.name").indexOf("Windows") == -1) {           	
                // 非windows 系统
                toPdfTool = SystemEnvironment.getApplicationFolder() + File.separator + "print" + File.separator + "tools"
                        + File.separator + "linux" + File.separator + "wkhtmltopdf";
                if(System.getProperty("os.arch").indexOf("aarch")!=-1){
                    toPdfTool = toPdfTool + "_arm";
                }
                String command1 = "chmod 777 " + toPdfTool;
                logger.info("转pdf得到的command1================================"+command1);
                Process process = Runtime.getRuntime().exec(command1);
                process.waitFor();
                initialized = true;
            }
        } catch (Exception e) {
            logger.error("LINUX 目录授权失败" + e.getMessage());
        }
    }
    public static boolean transHtmlToPdf(String htmlFilePath, String pdfFilePath) {
        if(!initialized){
            init();
        }
        String wkhtmltopdfToolPath = toPdfTool;
        String command = "";
        try {
            if (StringUtils.isNotBlank(wkhtmltopdfToolPath)) {
                CtpLocalFile file = new CtpLocalFile(htmlFilePath);
                if (!file.exists()) {
                    logger.info("PDF转换源文件不存在：" + htmlFilePath);
                    return false;
                }
                command = wkhtmltopdfToolPath + " --enable-local-file-access " + htmlFilePath + " " + pdfFilePath;
                logger.info("命令:"+command);
                exec(command);
                logger.info("转PDF成功:" + pdfFilePath);
                return true;
            }
        } catch (Exception e) {
            logger.info("命令："+command);
            logger.info("文单转PDF异常:" + e.getMessage());
        }
        return false;
    }
    private static void exec(String cmd) throws Exception {
        if(!Strings.isBlank(cmd)) {
            FutureTask<String> task = new FutureTask<String>(
                    new Callable<String>() {
                        public String call() throws Exception {
                            Process proc = Runtime.getRuntime().exec(cmd);
                            ExecutorServiceFactory.getDefaultThreadPool().submit(new HtmlToPdfInterceptor(proc.getErrorStream()));
                            ExecutorServiceFactory.getDefaultThreadPool().submit(new HtmlToPdfInterceptor(proc.getInputStream()));
                            proc.waitFor();
                            return "1";
                        }
                    });
            ExecutorServiceFactory.getDefaultThreadPool().execute(task);
            while (!task.isDone()) {
                Thread.sleep(1500);
            }
        }
    }
}
